package com.zhentao.subscription.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zhentao.subscription.domain.dto.TaskCreateDTO;
import com.zhentao.subscription.domain.entity.SubscriptionTask;
import com.zhentao.subscription.mapper.SubscriptionTaskMapper;
import com.zhentao.subscription.service.FileStorageService;
import com.zhentao.subscription.service.TaskService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.nio.file.Path;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl extends ServiceImpl<SubscriptionTaskMapper, SubscriptionTask> implements TaskService {

    private final FileStorageService fileStorageService;
    private final SubscriptionTaskMapper taskMapper;

    public TaskServiceImpl(FileStorageService fileStorageService, SubscriptionTaskMapper taskMapper) {
        this.fileStorageService = fileStorageService;
        this.taskMapper = taskMapper;
    }

    @Override
    public Long createOrUpdateTask(TaskCreateDTO dto) {
        SubscriptionTask task = new SubscriptionTask();
        if (dto.getId() != null) {
            task.setId(dto.getId());
        }

        // 基本信息
        task.setTaskName(dto.getTaskName());
        task.setTemplateId(dto.getTemplateId());
        task.setCustomsCode(dto.getCustomsCode());

        // 新增的必填字段
        task.setScopeType(dto.getScopeType());
        task.setSubscribeType(dto.getSubscribeType());
        task.setSubscribeMode(dto.getSubscribeMode());
        task.setDataFormat(dto.getDataFormat());
        task.setDataSource(dto.getDataSource());
        task.setTargetSystems(dto.getTargetSystems());

        // JSON字段
        task.setGroupFields(dto.getGroupFields());
        task.setNumericAggFields(dto.getNumericAggFields());
        task.setConditions(dto.getConditions());
        task.setSelectedFields(dto.getSelectedFields());

        // 其他字段
        task.setDataRange(dto.getDataRange());
        task.setStrongCheck(dto.getStrongCheck());
        task.setStatus(dto.getStatus() != null ? dto.getStatus() : "ACTIVE");
        task.setDispatchStatus(dto.getDispatchStatus() != null ? dto.getDispatchStatus() : "PENDING");

        // 日期字段
        task.setCloseDateStart(dto.getCloseDateStart());
        task.setCloseDateEnd(dto.getCloseDateEnd());

        // 文件字段
        task.setFileName(dto.getFileName());
        task.setFilePath(dto.getFilePath());

        // 调度信息（这些字段在数据库表中不存在，但保留以防前端还在使用）
        task.setScheduleType(dto.getScheduleType());
        task.setScheduleTime(dto.getScheduleTime());
        task.setScheduleCron(dto.getScheduleCron());

        this.saveOrUpdate(task);
        return task.getId();
    }

    @Override
    public Page<SubscriptionTask> pageTasks(int pageNo, int pageSize, String keyword) {
        LambdaQueryWrapper<SubscriptionTask> qw = new LambdaQueryWrapper<>();
        if (keyword != null && !keyword.isBlank()) {
            qw.like(SubscriptionTask::getTaskName, keyword);
        }
        qw.orderByDesc(SubscriptionTask::getUpdatedTime);
        return this.page(new Page<>(pageNo, pageSize), qw);
    }

    @Override
    public void deleteTask(Long id) {
        this.removeById(id);
    }

    @Override
    public void triggerDispatch(Long id) {
        SubscriptionTask task = this.getById(id);
        if (task == null) {
            throw new IllegalArgumentException("任务不存在");
        }

        try {
            String code = task.getCustomsCode() != null ? task.getCustomsCode() : "default";
            Path dir = fileStorageService.ensureTaskDir("CUSTOMS", code);
            String ts = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
            String filename = task.getTaskName().replaceAll("[^a-zA-Z0-9_-]", "_") + "_" + ts + ".csv";

            // TODO: 根据任务配置从数据库查询真实数据并导出
            // 这里先使用示例数据
            String content = "entry_id,g_no,i_e_flag\n" +
                    "E123456789012345,1,1\n";
            Path file = fileStorageService.saveCsv(dir, filename, content);
            fileStorageService.pruneKeepLatest(dir, 3);

            // 更新任务状态
            task.setStatus("ACTIVE");
            task.setLastRunTime(LocalDateTime.now());
            this.updateById(task);
        } catch (Exception e) {
            task.setStatus("INACTIVE");
            task.setLastRunTime(LocalDateTime.now());
            this.updateById(task);
            throw new RuntimeException("下发失败:" + e.getMessage(), e);
        }
    }

}

